<?php
class CurrencyComponent extends Object{
	var $components = array( 'Auth','Session','RequestHandler');
	var $StoreCurrency;
	
		/**
		 * pobranie pliku xml z nbp.pl
		 * @return unknown_type
		 */
		function refresch(){
//			Configure::write('debug', 0);
//			$this->autoRender = false;
			$this->StoreCurrency =& $this->getModel('StoreCurrency');
		    if(!$this->StoreCurrency){
		      return false;
		    }
		    $last_modified = $this->StoreCurrency->find('first',array('StoreCurrency.id != '=>'PLN'));		    
		    if(is_array($last_modified) && isset($last_modified['StoreCurrency']['modified']) && $last_modified['StoreCurrency']['modified'] < date('Y-m-d')){
		    	try{
					App::import('Xml');
					App::import('Core', 'HttpSocket');
					$HttpSocket = new HttpSocket();
					$file_name = $this->aktualny_xml();					
					$file = "http://www.nbp.pl/Kursy/xml/".$file_name.".xml";
					if(file_exists($file)){
						$results = $HttpSocket->get();
						
						$parsed_xml =& new XML($results,array('cdata'=>false));
						$parsed_arr = Set::reverse($parsed_xml); // this is what i call magic
			//			debug($parsed_arr['TabelaKursow']['Pozycja']);        
			
						if($last_modified['StoreCurrency']['modified'] == $parsed_arr['TabelaKursow']['data_publikacji'])
							return;
						foreach ($parsed_arr['TabelaKursow']['Pozycja'] as $key => $waluta) {
							$data = array();
							$data['id'] = $waluta['kod_waluty'];
							$data['name'] = $waluta['nazwa_waluty'];
							$data['conversion'] = $waluta['przelicznik'];
							$data['exchange'] = str_replace(',', '.', $waluta['kurs_sredni']);
							$data['modified'] = $parsed_arr['TabelaKursow']['data_publikacji'];
							$this->StoreCurrency->id = $waluta['kod_waluty'];
							$this->StoreCurrency->save($data);
						}
					}
		    	}catch (Exception $e){
		    		$this->Session->setFlash(__( $e->getMessage(), true));
		    	}
		    }
		}
		
		public function set(){
			$this->StoreCurrency =& $this->getModel('StoreCurrency');
		    if(!$this->StoreCurrency){
		      return false;
		    }
		    $default = $this->StoreCurrency->find('first',array('conditions'=>array('StoreCurrency.default'=>1)));
		  	
		    if(is_array($default) && isset($default['StoreCurrency']['id']) ){
		    	
			    $this->Session->write('Store.default_currency',$default['StoreCurrency']['id']);
				$this->Session->write('Store.default_conversion',$default['StoreCurrency']['conversion']);
				$this->Session->write('Store.default_exchange',$default['StoreCurrency']['exchange']);
				$this->Session->write('Store.default_symbol',$default['StoreCurrency']['symbol']);
				
			    $selected_currency = $this->Session->read('Store.selected_currency');
			    $selected_conversion = $this->Session->read('Store.selected_conversion');
			    $selected_exchange = $this->Session->read('Store.selected_exchange');
			    $selected_symbol = $this->Session->read('Store.selected_symbol');
				if(empty($selected_currency) || empty($selected_conversion) || empty($selected_exchange) || empty($selected_symbol)){
					$this->Session->write('Store.selected_currency',$default['StoreCurrency']['id']);
					$this->Session->write('Store.selected_conversion',$default['StoreCurrency']['conversion']);
					$this->Session->write('Store.selected_exchange',$default['StoreCurrency']['exchange']);
					$this->Session->write('Store.selected_symbol',$default['StoreCurrency']['symbol']);
				}
				$def = $this->Session->read('Store');
				return true;
		    }else{
				return false;
		    }
		}
		
		public function get_list(){
		$this->StoreCurrency =& $this->getModel('StoreCurrency');
		    if(!$this->StoreCurrency){
		      return false;
		    }
			return $this->StoreCurrency->find('list',array('conditions'=>array('StoreCurrency.active'=> 1)));
		}

		/**
		 * ustalenie nazwy pliki z aktualnymi kursami
		 * @param unknown_type $strTabela
		 * @return unknown_type
		 */
		private function aktualny_xml($strTabela='a'){
		 $strDzisiejszyXML = '';
		 $fp = @fsockopen("www.nbp.pl", 80, $errno, $errstr, 30);
		 if (!$fp) {
				throw new Exception("Brak polaczenia z tabela kursow NBP");
		 }else {
		 	$out = "GET /Kursy/xml/dir.txt HTTP/1.1\r\n";
		 	$out .= "Host: www.nbp.pl\r\n";
		 	$out .= "Connection: Close\r\n\r\n";
		 	fwrite($fp, $out);
		 	while (!feof($fp)) {
		 		$arrPlikiXML[] = fgets($fp, 128);
		 	}
		 	fclose($fp);
		 }
		 $arrPlikiXML = array_reverse ($arrPlikiXML);
		 for($i=0; $i<=6; $i++){
		 	$strNazwa=trim($arrPlikiXML[$i]);
		 	if(substr($strNazwa,0,1)==$strTabela){
		 		$strDzisiejszyXML=trim($arrPlikiXML[$i]);
		 		break;
		 	}
		 }
		 return $strDzisiejszyXML;
		}
		
	function &getModel($name = null) {
		$model = null;
		if (!$name) {
			$name = 'StoreProduct';
		}    
		if($name){
			if (PHP5) {
				$model = ClassRegistry::init($name);
			} else {
				$model =& ClassRegistry::init($name);
			}

			if (empty($model)) {
//				$this->_error('FileUpload::getModel() - Model is not set or could not be found');
				return null;
			}
		}
		return $model;
	}	
}